#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   controllers.py
@Time    :   2024/02/06 11:50:25
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from ninja_extra import api_controller, route, status
from ninja_extra.permissions import IsAuthenticated
from ninja_jwt.authentication import JWTAuth

from .schema import ArticleSchema,CreateArticleSchema
from .mixins import ArticleViewMixin
from core.schemas import ErrorSchema


@api_controller(
    "/article", tags=["文章管理"], permissions=[IsAuthenticated], auth=JWTAuth()
)
class ArticleController(ArticleViewMixin):

    @route.get(
        "/list",
        summary="文章列表",
        url_name="article-list",
        response=list[ArticleSchema],
    )
    def get_article_list(
        self,
    ):
        return self.get_queryset()

    @route.get(
        "/info/{id}",
        summary="文章详情",
        url_name="article-detail",
        response=ArticleSchema,
    )
    def get_article_detail(self, id: int):
        obj = self.get_object_or_exception(
            self.get_queryset(),
            id=id,
            error_message="文章ID不存在",
        )
        return obj
    
    @route.post(
        "/add",
        summary="创建文章",
        url_name="article-create",
        response=[(201, ArticleSchema), (400, ErrorSchema)],
    )
    def create_article(self, article: CreateArticleSchema):
        try:
            article = article.create_obj()
            return 201, article
        except Exception as ex:
            return 400, dict(details=str(ex))

    
    @route.delete(
        "/delete/{id}",
        summary="删除文章",
        url_name="article-delete",
        response={204: dict},
    )
    def delete_article(self, id: int):
        obj = self.get_object_or_exception(
            self.get_queryset(),
            id=id,
            error_message="文章ID不存在",
        )
        obj.delete()
        return self.create_response(
            "文章已删除", status_code=status.HTTP_204_NO_CONTENT
        )

    @route.put(
        "/update/{id}",
        summary="更新文章",
        url_name="article-update",
        response=ArticleSchema,
    )
    def update_article(self, id: int, article: CreateArticleSchema):
        obj = self.get_object_or_exception(
            self.get_queryset(),
            id=id,
            error_message="文章ID不存在",
        )
        article.update(obj)
        return obj
    
